import java.io.*;
import java.net.*;

public class JServer {
  static public String sharedDoc = "";
  public static void main(String[] args) throws IOException {
    ServerSocket mainSocket = new ServerSocket(9000);
    while(true) {
      System.out.println("Server is listening...");
      Socket commSocket = mainSocket.accept();
      System.out.println(" > connection made");
      InputStream input = commSocket.getInputStream();
      OutputStream output = commSocket.getOutputStream();

      handle(input, output);

      commSocket.close();
    }
  }

  public static void handle(InputStream in, OutputStream out) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    PrintWriter writer = new PrintWriter(out);
    // Read the instruction
    //
    String instruct = reader.readLine();
    System.out.println(" > instruction=" + instruct);
    if(instruct.equals("put")) {
      String line = reader.readLine();
      JServer.sharedDoc += line + "\n";
      System.out.println(" > message=" + line);
      System.out.println(" ----------\n" + sharedDoc);
    } else {
      System.out.println(" ----------\n" + sharedDoc);
      writer.println(JServer.sharedDoc);
      writer.flush();
    }
  }
}
